#include "sonic.h"
#include <intrins.h>

void Delay12us(void)	//@12.000MHz
{
	unsigned char data i;

	_nop_();
	_nop_();
	i = 33;
	while (--i);
}


void sonic_init() {
	uchar i;
	
	for(i=0; i<8; i++) {
		TX = 1;
		Delay12us();
		TX = 0;
		Delay12us();
	}
}


uchar sonic_read(uint tran_speed) {
	uint time;
	
	CMOD &= 0x00;
	CH = CL = 0;
	
	sonic_init();
	CR = 1;
	
	while(RX && !CF);
	
	CR = 0;
	if(!CF) {
		time = (CH << 8) | CL;
		return (tran_speed*time)/20000;
	} else {
		CF = 0;
		return 255;
	}
}
